import { mqttClient } from "../config/mqtt";

export const publish = (topic: string, payload: any) => {
  const message =
    typeof payload === "string" ? payload : JSON.stringify(payload);
  mqttClient.publish(topic, message, { qos: 1 }, (err) => {
    if (err) {
      console.error(`[MQTT] Failed to publish to ${topic}:`, err.message);
    } else {
      console.log(`[MQTT] Published to ${topic}`);
    }
  });
};

export const subscribe = (
  topic: string,
  handler: (message: string) => void
) => {
  mqttClient.subscribe(topic, { qos: 1 }, (err) => {
    if (err) {
      console.error(`[MQTT] Failed to subscribe ${topic}:`, err.message);
    } else {
      console.log(`[MQTT] Subscribed to ${topic}`);
    }
  });

  mqttClient.on("message", (receivedTopic, payload) => {
    if (receivedTopic === topic) {
      try {
        handler(payload.toString());
      } catch (err) {
        console.error("[MQTT] Handler error:", err);
      }
    }
  });
};
